package com.csm.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csm.admin.bean.User;
import com.csm.admin.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


/**
 * @author csm
 */
@Controller
public class TableController {

    @Autowired
    UserService userService;

    @GetMapping("/basic_table")
    public String basicTable() {
        return "table/basic_table";
    }

    @GetMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable("id") Long id,
                             @RequestParam(value = "pn", defaultValue = "1")Integer pn,
                             RedirectAttributes ra
                             ) {
        userService.removeById(id);

        ra.addAttribute("pn", pn);
        return "redirect:/dynamic_table";
    }

    // 跳转到修改页面
    //通过@PathVariable注解，将占位符所表示的数据赋值给控制器方法的形参
    @GetMapping("/toUpdateUser/{id}")
    public String toUpdateBook(@PathVariable("id") int id, Model model) {
        User byId = userService.getById(id);
        model.addAttribute("QUser", byId);

        return "/updateUser";
    }

    @GetMapping("/updateUser")
    public String updateBook(User user,
                             @RequestParam(value = "pn", defaultValue = "1")Integer pn,
                             RedirectAttributes ra) {
        System.out.println("updateBook =>" + user);
        boolean b = userService.updateById(user);
        if (b) {
            ra.addAttribute("pn", pn);
            return "redirect:/dynamic_table";
        }
        return "error";
    }

    @GetMapping("/dynamic_table")
    public String dynamicTable(@RequestParam(value = "pn", defaultValue = "1")Integer pn, Model model) {
//        //表格内容的遍历
//        List<User1> user1s = Arrays.asList(new User1("zhangsan", "123456"),
//                new User1("lili", "123444"),
//                new User1("haha", "aaaaa"),
//                new User1("hehe", "aaddd")
//        );
//        model.addAttribute("users", user1s);

        //从数据库中查出user表中的用户进行展示
        //构造分页参数
        Page<User> page = new Page<>(pn, 2);
        //调用page进行分页
        Page<User> userPage = userService.page(page, null);


//        userPage.getRecords()
//        userPage.getCurrent()
//        userPage.getPages()


        model.addAttribute("users",userPage);
        return "table/dynamic_table";
    }

    @GetMapping("/responsive_table")
    public String responsiveTable() {
        return "table/responsive_table";
    }

    @GetMapping("/editable_table")
    public String editableTable() {
        return "table/editable_table";
    }
}
